package com.cpfmat.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.cpfmat.common.CommonStringUtils;
import com.cpfmat.common.LogUtils;
import com.cpfmat.common.MailPropertyUtil;
import com.cpfmat.common.SendEmail;
import com.cpfmat.entity.OtherUser;
import com.cpfmat.entity.YzmTab;
import com.cpfmat.service.IOtherUserService;
import com.cpfmat.service.IRzTabService;
import com.cpfmat.service.IYzmTabService;

@Controller
public class OtherUserController {

	private class SMSThread extends Thread {
		private String phonenum, yzm;

		public SMSThread(String phonenum, String yzm) {
			this.phonenum = phonenum;
			this.yzm = yzm;
		}

		@Override
		public void run() {
			sendSMS(this.phonenum, this.yzm);
		}
	}

	private class SendEmailThread extends Thread {
		private String email, uuid, yzm;
		private HttpServletRequest request;

		public SendEmailThread(String email, String uuid, String yzm) {
			this.email = email;
			this.uuid = uuid;
			this.yzm = yzm;
		}

		public SendEmailThread(String email, String uuid, String yzm, HttpServletRequest request) {
			this.email = email;
			this.uuid = uuid;
			this.yzm = yzm;
			this.request = request;
		}

		@Override
		public void run() {
			if (this.request != null) {
				sendEmail(this.email, this.uuid, this.yzm, this.request);
			} else {
				sendEmail2(this.email, this.uuid, this.yzm);
			}
		}
	}

	@Autowired
	private IOtherUserService otherUserService;
	@Autowired
	private IYzmTabService yzmTabService;
	@Autowired
	private IRzTabService reTabService;

	@RequestMapping(path = "/otherLogin")
	public ModelAndView init(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/otherLogin");
		view.addObject("onlyCollection", request.getParameter("onlyCollection"));
		return view;
	}

	@RequestMapping("/userlogout")
	public ModelAndView logout(HttpServletRequest request) {
		OtherUser loginUser = CommonStringUtils.getUserFromRequest(request);
		if (loginUser != null) {
			reTabService.log(loginUser.getSqlId(), "登出", CommonStringUtils.getIpAddress(request), null);
		}

		request.getSession().invalidate();

		ModelAndView view = new ModelAndView("/index");
		return view;
	}

	@RequestMapping("/login2")
	public ModelAndView login2(String loginName, String password, HttpServletRequest request)

			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		password = CommonStringUtils.md5(password);

		OtherUser user2 = otherUserService.checkLogin(loginName, password);

		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			if (user2.getYzbz() != null && user2.getYzbz().equals("Y")) {

				reTabService.log(user2.getSqlId(), "登录", CommonStringUtils.getIpAddress(request), null);

				request.getSession().setAttribute("otherLoginUser", user2);
				
				String onlyCollection = request.getParameter("onlyCollection");
				
				if("true".equals(onlyCollection)) {
					ModelAndView view = new ModelAndView("redirect:/sendAtri");
					view.addObject("onlyCollection", onlyCollection);
					view.addObject("pageNum", "1");
					return view;
				}
				else {
					return new ModelAndView("redirect:/index");
				}
			} else {
				ModelAndView view = new ModelAndView("/reYz");
				view.addObject("yzId", user2.getSqlId());
				return view;
			}
		} else {
			ModelAndView view = new ModelAndView("/otherLogin");

			view.addObject("loginError", true);
			view.addObject("ErrorCode", "登录失败，用户名/密码不正确");
			return view;
		}
	}

	@RequestMapping("/login2/")
	public ModelAndView login2Null() {
		ModelAndView view = new ModelAndView("/otherLogin");

		view.addObject("loginError", true);
		view.addObject("ErrorCode", "登录失败，账户不存在");
		return view;
	}

	@RequestMapping(path = "/register")
	public ModelAndView registerPage() {
		ModelAndView view = new ModelAndView("/registerPage");
		return view;
	}

	@RequestMapping(path = "/chenagReturn")
	public ModelAndView chenagReturn() {
		ModelAndView view = new ModelAndView("redirect:/changPasswordStart");
		return view;
	}

	@RequestMapping(path = "/changPasswordStart")
	public ModelAndView changePasswordStart() {
		ModelAndView view = new ModelAndView("/otherUser/changePasswordHomePage");
		return view;
	}

	@RequestMapping("/changPassword")
	public ModelAndView changePassword(String loginName) {
		OtherUser user2 = otherUserService.hasUserByloginName(loginName);
		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			ModelAndView view = new ModelAndView("/otherUser/changePassword");
			view.addObject("uuid", user2.getSqlId());
			return view;
		} else {
			ModelAndView view = new ModelAndView("/otherUser/changeResult");
			view.addObject("returnMessage", "该用户并不存在，请重试");
			return view;
		}
	}

	@RequestMapping("/changeFunction")
	public ModelAndView changeFunction(String uuid, String yzfs, HttpServletRequest request) {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			if (yzfs.equals("DX")) {
				String yzm = getYzm(uuid, "XG");
				this.sendSMS(user2.getPhonenum(), yzm);
				ModelAndView view = new ModelAndView("/otherUser/changeLastPage");
				view.addObject("uuid", user2.getSqlId());
				
				String contactNum = user2.getPhonenum();
				view.addObject("contactNum", contactNum);
				
				view.addObject("function", "DX");
				view.addObject("userName", user2.getUserName());
				return view;
			} else if (yzfs.equals("YX")) {

				ModelAndView view = new ModelAndView("/otherUser/changeByEmail");
				
				String contactNum = user2.getEmail();
				view.addObject("contactNum", contactNum);
				
				view.addObject("uuid", user2.getSqlId());
				return view;
			} else {
				ModelAndView view = new ModelAndView("/otherUser/changeResult");
				view.addObject("returnMessage", "验证方式不正确，请重试");
				return view;
			}
		} else {
			ModelAndView view = new ModelAndView("/otherUser/changeResult");
			view.addObject("returnMessage", "该用户并不存在，请重试");
			return view;
		}
	}

	@RequestMapping("/changeByEmail")
	public ModelAndView changeByEmail(String uuid, String email, HttpServletRequest request) {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			if (email.equals(user2.getEmail())) {
				String yzm = getYzm(uuid, "XG");
				SendEmailThread sendEmailThread = new SendEmailThread(user2.getEmail(), uuid, yzm);
				sendEmailThread.start();

				ModelAndView view = new ModelAndView("/otherUser/changeLastPage");
				view.addObject("uuid", user2.getSqlId());
				view.addObject("function", "YX");
				view.addObject("userName", user2.getUserName());
				return view;
			} else {
				ModelAndView view = new ModelAndView("/otherUser/changeResult");
				view.addObject("returnMessage", "邮件发送失败，请确认您输入的邮箱与您注册的邮箱是否一致");
				return view;
			}
		} else {
			ModelAndView view = new ModelAndView("/otherUser/changeResult");
			view.addObject("returnMessage", "该用户并不存在，请重试");
			return view;
		}
	}

	@RequestMapping("/changePasswordResult")
	public ModelAndView changPasswordResult(String function, String loginPwd, String reLoginPwd, String uuid,
			String yzm, HttpServletRequest request)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		
		YzmTab tab = yzmTabService.getBeanByYzId(uuid, "XG");

		if (!loginPwd.equals(reLoginPwd)) {
			ModelAndView view = new ModelAndView("/otherUser/changeLastPage");
			view.addObject("uuid", user2.getSqlId());
			view.addObject("function", function);
			view.addObject("userName", user2.getUserName());
			
			String contactNum = null;
			if("DX".equals(function)){
				contactNum = user2.getPhonenum();
			}
			else if("YX".equals(function)){
				contactNum = user2.getEmail();
			}
			view.addObject("contactNum", contactNum);
			
			view.addObject("ErrorCode", "两次输入的密码不一致！");
			return view;
		}
		else if(!tab.getYzm().equals(yzm)){
			ModelAndView view = new ModelAndView("/otherUser/changeLastPage");
			view.addObject("uuid", user2.getSqlId());
			view.addObject("function", function);
			view.addObject("userName", user2.getUserName());
			view.addObject("ErrorCode", "验证码错误！");
			
			String contactNum = null;
			if("DX".equals(function)){
				contactNum = user2.getPhonenum();
			}
			else if("YX".equals(function)){
				contactNum = user2.getEmail();
			}
			view.addObject("contactNum", contactNum);
			
			return view;
		}
		else {
			reTabService.log(uuid, "成功修改密码", CommonStringUtils.getIpAddress(request), null);

			loginPwd = CommonStringUtils.md5(loginPwd);
			user2.setLoginPwd(loginPwd);
			otherUserService.customUpdate(user2);
			ModelAndView view = new ModelAndView("/otherUser/changeResult");
			view.addObject("flag", "success");
			view.addObject("returnMessage", "修改密码成功");
			return view;
		}
	}

	@RequestMapping(path = "/reSendSMS")
	@ResponseBody
	public ModelAndView resSendSMS(String yzId) {
		// boolean result = false;

		OtherUser user = otherUserService.checkUserById(yzId);
		ModelAndView view = new ModelAndView("/dxyz");

		if (user != null) {
			YzmTab yzmTab = yzmTabService.getBeanByYzId(yzId, "ZC");

			String phonenum = user.getPhonenum();
			view.addObject("phonenum", phonenum.substring(0, 3) + "****" + phonenum.substring(7, phonenum.length()));

			if (yzmTab != null) {
				if (new Date().getTime() < new Long(yzmTab.getYxsj()).longValue()) {

					this.sendSMS(user.getPhonenum(), yzmTab.getYzm());
					// result = true;
				} else {
					yzmTabService.deleteById(yzmTab);
					// String yzm = this.getYzm(yzId, "ZC");
					this.sendSMS(user.getPhonenum(), yzmTab.getYzm());
					// result = true;
				}
			} else {
				String yzm = this.getYzm(yzId, "ZC");
				this.sendSMS(user.getPhonenum(), yzm);
			}
		} else {
			view.setViewName("otherLogin");
		}
		view.addObject("yzId", yzId);
		return view;
	}

	@RequestMapping(path = "/reSendEmail")
	public ModelAndView reSendEmail(String yzId, HttpServletRequest request) {
		// boolean result = false;
		YzmTab yzmTab = yzmTabService.getBeanByYzId(yzId, "ZC");

		OtherUser user = otherUserService.checkUserById(yzId);
		ModelAndView view = new ModelAndView("/yxyzfhjm");

		if (user != null) {
			if (yzmTab != null) {
				if (new Date().getTime() < new Long(yzmTab.getYxsj()).longValue()) {

					SendEmailThread sendEmailThread = new SendEmailThread(user.getEmail(), yzId, yzmTab.getYzm(),
							request);
					sendEmailThread.start();

					// result = true;
				} else {
					yzmTabService.deleteById(yzmTab);
					// String yzm = this.getYzm(yzId, "ZC");

					SendEmailThread sendEmailThread = new SendEmailThread(user.getEmail(), yzId, yzmTab.getYzm(),
							request);
					sendEmailThread.start();
					// result = true;
				}
			} else {
				String yzm = this.getYzm(yzId, "ZC");
				this.sendEmail(user.getEmail(), yzId, yzm, request);
			}
		} else {
			view.setViewName("otherLogin");
		}
		view.addObject("yzId", yzId);
		return view;
	}

	@RequestMapping("/reYz")
	public ModelAndView reYz(String yzId, String yzfs, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/reYz");

		OtherUser user = otherUserService.checkUserById(yzId);
		if (user != null) {
			YzmTab yzmTab = yzmTabService.getBeanByYzId(yzId, "ZC");
			if ("DX".equals(yzfs)) {
				if (yzmTab != null) {
					if (new Date().getTime() < new Long(yzmTab.getYxsj()).longValue()) {
						this.sendSMS(user.getPhonenum(), yzmTab.getYzm());
					} else {
						yzmTabService.deleteById(yzmTab);
						this.sendSMS(user.getPhonenum(), yzmTab.getYzm());
					}
				} else {
					String yzm = this.getYzm(yzId, "ZC");
					this.sendSMS(user.getPhonenum(), yzm);
				}
				String phonenum = user.getPhonenum();
				view.addObject("phonenum",
						phonenum.substring(0, 3) + "****" + phonenum.substring(7, phonenum.length()));
				view.setViewName("/dxyz");
				view.addObject("yzId", yzId);
				return view;
			} else if ("YX".equals(yzfs)) {
				if (yzmTab != null) {
					if (new Date().getTime() < new Long(yzmTab.getYxsj()).longValue()) {

						SendEmailThread sendEmailThread = new SendEmailThread(user.getEmail(), yzId, yzmTab.getYzm(),
								request);
						sendEmailThread.start();

					} else {
						yzmTabService.deleteById(yzmTab);
						// String yzm = this.getYzm(yzId, "ZC");
						SendEmailThread sendEmailThread = new SendEmailThread(user.getEmail(), yzId, yzmTab.getYzm(),
								request);
						sendEmailThread.start();
					}
				} else {
					String yzm = this.getYzm(yzId, "ZC");
					this.sendEmail(user.getEmail(), yzId, yzm, request);
				}
				view.setViewName("/yxyzfhjm");
				view.addObject("yzId", yzId);
				return view;
			}
		} else {
			view.setViewName("/otherLogin");
		}

		view.addObject("yzId", yzId);
		view.addObject("ErrorCode", "激活出现异常，请重新激活");
		return view;

	}

	@RequestMapping("/registerSave")
	public ModelAndView register(String loginName, String userName, String reLoginPwd, String loginPwd, String phonenum,
			String email, String yzfs, @RequestParam(required = false) String ssdw,
			@RequestParam(required = false) String yzm, HttpServletRequest request)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		boolean loginError = false;

		ModelAndView view = new ModelAndView("/registerPage");

		view.addObject("loginName", loginName);
		view.addObject("userName", userName);
		view.addObject("reLoginPwd", reLoginPwd);
		view.addObject("loginPwd", loginPwd);
		view.addObject("phonenum", phonenum);
		view.addObject("email", email);
		view.addObject("yzfs", yzfs);
		view.addObject("ssdw", ssdw);

		if (StringUtils.isBlank(loginName)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("loginNameCode", "用户名不能为空");
		}
		if (StringUtils.isBlank(userName)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("userNameCode", "中文名称不能为空");
		}
		if (StringUtils.isBlank(loginPwd)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("loginPwdCode", "密码不能为空");
		}
		if (StringUtils.isBlank(reLoginPwd)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("reLoginPwdCode", "确认密码不能为空");
		}
		if (StringUtils.isBlank(phonenum)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("phonenumCode", "手机不能为空");
		}
		if (StringUtils.isBlank(email)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("emailCode", "E-mail不能为空");
		}
		if (StringUtils.isBlank(yzfs)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("yzfsCode", "验证方式不能为空");
		}
		if (!CommonStringUtils.validate(yzm, request)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("yzmCode", "请输入正确的验证码");
		}

		if (loginError) {
			return view;
		}

		if (loginName.trim().length() > 20) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("loginNameCode", "用户名不能超过20个字符");
		}
		if (userName.trim().length() > 20) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("userNameCode", "中文名称不能超过20个字符");
		}
		if (loginPwd.trim().length() > 20) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("loginPwdCode", "密码不能不能超过20个字符");
		} else if (!loginPwd.equals(reLoginPwd)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("reLoginPwdCode", "确认密码与密码不一致");
		}
		if (!CommonStringUtils.validatePhone(phonenum)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("phonenumCode", "手机号码格式不正确");
		}
		if (email.trim().length() > 50) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("emailCode", "E-mail不能超过50个字符");
		} else if (!CommonStringUtils.validateEmail(email)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("emailCode", "E-mail格式不正确");
		}
		if(ssdw.trim().length() > 200) {
			view.addObject("loginError", loginError);
			view.addObject("ssdwCode", "所属单位长度不能超过200个字符");
		}

		if (loginError) {
			return view;
		}

		OtherUser user1 = otherUserService.hasUserByEmail(email);
		OtherUser user2 = otherUserService.hasUserByloginName(loginName);
		OtherUser user3 = otherUserService.hasUserByPhonenum(phonenum);

		if ((user1 != null) && (user1.getDelFlag() == 0)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("ErrorCode", "该邮箱已经被注册使用，请勿重复注册");
		}

		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("ErrorCode", "该用户名已经被注册使用，请勿重复注册");
		}

		if ((user3 != null) && (user3.getDelFlag() == 0)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("ErrorCode", "该手机号已经被注册使用，请勿重复注册");
		}

		if (loginError) {
			return view;
		}

		loginPwd = CommonStringUtils.md5(loginPwd);

		String uuid = CommonStringUtils.getUUID();
		Date nowTime = new Date();
		OtherUser user = new OtherUser();
		user.setSqlId(uuid);
		user.setDelFlag(0);
		user.setLoginName(loginName);
		user.setLoginPwd(loginPwd);
		user.setUpdateCounts(0);
		user.setUpdateTime(nowTime);
		user.setUserName(userName);
		user.setPhonenum(phonenum);
		user.setEmail(email);
		user.setSsdw(ssdw);
		user.setYzbz("N");
		user.insert();
		String sendYzm = this.getYzm(uuid, "ZC");
		if ("DX".equals(yzfs)) {
			SMSThread smsThread = new SMSThread(phonenum, sendYzm);
			smsThread.start();

			view.setViewName("/dxyz");
			view.addObject("yzId", uuid);
			view.addObject("phonenum", phonenum.substring(0, 3) + "****" + phonenum.substring(7, phonenum.length()));
			return view;
		} else if ("YX".equals(yzfs)) {
			SendEmailThread sendEmailThread = new SendEmailThread(email, uuid, sendYzm, request);
			sendEmailThread.start();

			view.setViewName("/yxyzfhjm");
			view.addObject("yzId", uuid);
			return view;
		}

		reTabService.log(uuid, "注册", CommonStringUtils.getIpAddress(request), null);

		return view;
	}

	@RequestMapping("/yzService")
	public ModelAndView yzService(String yzId, String yzm, HttpServletRequest request) {
		YzmTab yzmTab = yzmTabService.getBeanByYzId(yzId, "ZC");
		if (yzmTab != null) {
			if (yzmTab.getYzm().equals(yzm)) {
				if (new Date().getTime() < new Long(yzmTab.getYxsj()).longValue()) {
					OtherUser user = otherUserService.checkUserById(yzId);
					if (user != null) {
						if (user.getYzbz().equals("Y")) {
							ModelAndView view = new ModelAndView("/yzresult");
							view.addObject("result", "该用户已激活，无需重复激活");
							return view;
						} else {
							reTabService.log(user.getSqlId(), "激活成功", CommonStringUtils.getIpAddress(request), null);

							user.setYzbz("Y");
							otherUserService.customUpdate(user);
							ModelAndView view = new ModelAndView("/yzresult");
							view.addObject("result", "恭喜激活成功");
							return view;
						}
					} else {
						ModelAndView view = new ModelAndView("/otherLogin");
						return view;
					}
				} else {
					ModelAndView view = new ModelAndView("/reYz");
					view.addObject("ErrorCode", "验证码超时，请重新获取验证码");
					view.addObject("yzId", yzId);
					return view;
				}
			} else {
				ModelAndView view = new ModelAndView("/reYz");
				view.addObject("ErrorCode", "验证失败，请重新获取验证码");
				view.addObject("yzId", yzId);

				return view;
			}
		} else {
			ModelAndView view = new ModelAndView("/reYz");
			view.addObject("ErrorCode", "验证失败，请重新获取验证码");
			view.addObject("yzId", yzId);
			return view;
		}
	}

	@RequestMapping("/generateAdministrator2")
	@ResponseBody
	public String generateAdministrator(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException {

		if ("cpfmat".equals(key)) {
			OtherUser user = new OtherUser();
			String uuid = CommonStringUtils.getUUID();

			String password = CommonStringUtils.md5("123456");
			Date nowTime = new Date();

			user.setSqlId(uuid);
			user.setDelFlag(0);
			user.setLoginName("admin1");
			user.setLoginPwd(password);
			user.setUpdateCounts(0);
			user.setUpdateTime(nowTime);
			user.setUserName("军民网站后台管理员");
			user.insert();
			return "SUCCES";
		} else {
			return "ERROR KEY!";
		}

	}

	private void sendSMS(String phonenum, String yzm) {
		// 设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = "LTAIIUvKJDMiBwXw";// 你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = "CZzvPVmqDApaxxZxHdoeHNyHPKOgkP";// 你的accessKeySecret，参考本文档步骤2
		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
		request.setPhoneNumbers(phonenum);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName("天津军民科技协同创新平台");
		// 必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
		request.setTemplateCode("SMS_143714133");
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		request.setTemplateParam("{\"code\":\"" + yzm + "\"}");
		// 可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		request.setOutId("yourOutId");
		// 请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = null;
		try {
			sendSmsResponse = acsClient.getAcsResponse(request);
		} catch (ServerException e) {

			e.printStackTrace();
		} catch (ClientException e) {

			e.printStackTrace();
		}
		if (sendSmsResponse.getCode() != null) {
			// 请求成功
			System.out.println(sendSmsResponse.getCode());
		}
	}

	private void sendEmail(String email, String uuid, String yzm, HttpServletRequest request) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("您好，");
		buffer.append("请点击下面的链接完成注册：");
		buffer.append(CommonStringUtils.getBasePath(request));
		buffer.append("/yzService?");
		buffer.append("yzId=" + uuid + "&amp;yzm=" + yzm);
		try {
			SendEmail.sendMessage(MailPropertyUtil.getProperty("smtpHost"), MailPropertyUtil.getProperty("userName"),
					MailPropertyUtil.getProperty("password"), email, MailPropertyUtil.getProperty("signName"),
					buffer.toString(), "text/html;charset=gb2312");
		} catch (MessagingException e) {

			e.printStackTrace();
		}

	}

	private void sendEmail2(String email, String uuid, String yzm) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("您好，");
		buffer.append("您本次修改密码的验证码为：");
		buffer.append(yzm);
		try {
			SendEmail.sendMessage(MailPropertyUtil.getProperty("smtpHost"), MailPropertyUtil.getProperty("userName"),
					MailPropertyUtil.getProperty("password"), email, MailPropertyUtil.getProperty("signName"),
					buffer.toString(), "text/html;charset=gb2312");
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	private String getYzm(String yzid, String yzms) {

		YzmTab tab = yzmTabService.getBeanByYzId(yzid, yzms);
		if (tab != null) {
			long now = new Date().getTime();
			if (now < new Long(tab.getYxsj()).longValue()) {
				return tab.getYzm();
			} else {
				yzmTabService.deleteById(tab);
			}
		}
		tab = new YzmTab();
		int intFlag = (int) (Math.random() * 1000000);

		String flag = String.valueOf(intFlag);
		if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
			System.out.println(intFlag);
		} else {
			intFlag = intFlag + 100000;
			System.out.println(intFlag);
		}

		String uuid = CommonStringUtils.getUUID();

		tab.setSqlId(uuid);
		tab.setYzm(new Integer(intFlag).toString());
		tab.setQssj(new Long(new Date().getTime()).toString());
		tab.setYxsj(new Long(new Date().getTime() + 5 * 60 * 1000).toString());
		tab.setYzms(yzms);
		tab.setYzId(yzid);
		tab.insert();
		return new Integer(intFlag).toString();
	}

	@RequestMapping("/checkLoginName")
	@ResponseBody
	public boolean checkLoginName(String loginName) {
		OtherUser user2 = otherUserService.hasUserByloginName(loginName);
		return (user2 != null) && (user2.getDelFlag() == 0);
	}
	
	@RequestMapping("/checkEmail")
	@ResponseBody
	public String checkEmail(String uuid, String email) throws UnsupportedEncodingException {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			if (email.equals(user2.getEmail())) {
				return "success";
			} else {
				return "EM_NE";
			}
		} else {
			return "EM_EN";
		}
	}
	
	@RequestMapping("/checkPhone")
	@ResponseBody
	public String checkPhone(String uuid,String phone) {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		if ((user2 != null) && (user2.getDelFlag() == 0)) {
			if (phone.equals(user2.getPhonenum())) {
				return "success";
			} else {
				return "短信发送失败，请确认您输入的手机号码与您注册的手机号码是否一致";
			}
		} else {
			return "该手机号码对应的用户并不存在，请重试";
		}
	}
	
	/**
	 * 
	 * @param type
	 * @param uuid
	 * @return
	 */
	@RequestMapping("/retrieve")
	@ResponseBody
	public String retrieve(String type, String uuid,
			@RequestParam(required = false, name = "isRegister") Boolean isRegister) {
		OtherUser user2 = otherUserService.checkUserById(uuid);
		
		String identifyingCodeType = isRegister != null && isRegister.equals(true) ? "ZC" : "XG";
		
		try{
			if (type.equalsIgnoreCase(("YX"))) {
				String yzmTab = genNewIdentifyingCode(uuid, identifyingCodeType);
	
				SendEmailThread sendEmailThread = new SendEmailThread(user2.getEmail(), uuid, yzmTab);
				sendEmailThread.start();
				
				return "success";
			} else if (type.equalsIgnoreCase("DX")) {
				String yzmTab = genNewIdentifyingCode(uuid, identifyingCodeType);
				
				SMSThread smsThread = new SMSThread(user2.getPhonenum(), yzmTab);
				smsThread.start();
				
				return "success";
			} else {
				return "TP_ER";
			}
		} catch(Exception e){
			LogUtils.error(e);
			e.printStackTrace();
			return "UK_ER";
		}
	}
	
	/**
	 * 直接获取新的验证码
	 * @param yzid
	 * @param yzms
	 * @return
	 */
	private String genNewIdentifyingCode(String yzid, String yzms){
		YzmTab tab = yzmTabService.getBeanByYzId(yzid, yzms);
		if (tab != null) {
			yzmTabService.deleteById(tab);
		}
		tab = new YzmTab();
		int intFlag = (int) (Math.random() * 1000000);

		String flag = String.valueOf(intFlag);
		if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
			System.out.println(intFlag);
		} else {
			intFlag = intFlag + 100000;
			System.out.println(intFlag);
		}

		String uuid = CommonStringUtils.getUUID();

		tab.setSqlId(uuid);
		tab.setYzm(new Integer(intFlag).toString());
		tab.setQssj(new Long(new Date().getTime()).toString());
		tab.setYxsj(new Long(new Date().getTime() + 5 * 60 * 1000).toString());
		tab.setYzms(yzms);
		tab.setYzId(yzid);
		tab.insert();
		return new Integer(intFlag).toString();
	}
}
